package org.zebra.satoken;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.zebra.common.core.Result;
import org.zebra.common.exception.StatusCode;

import javax.servlet.http.HttpServletRequest;

import static cn.dev33.satoken.exception.NotLoginException.TOKEN_TIMEOUT;

/**
 * SaToken异常处理器
 *
 * @author zhanghongbin
 */
@Slf4j
@RestControllerAdvice
@Order(100)
public class SaTokenExceptionAdvice {

    private static Result<?> error(Integer code, String msg) {
        return new Result().toBuilder().code(code).msg(msg).build();
    }

    /**
     * 权限码异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public Result<?> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限码校验失败'{}'", requestURI, e.getMessage());
        return error(StatusCode.PERMISSION_FAILED.getCode(), StatusCode.PERMISSION_FAILED.getMsg());
    }

    /**
     * 角色权限异常
     */
    @ExceptionHandler(NotRoleException.class)
    public Result<?> handleNotRoleException(NotRoleException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',角色权限校验失败'{}'", requestURI, e.getMessage());
        return error(StatusCode.PERMISSION_FAILED.getCode(), StatusCode.PERMISSION_FAILED.getMsg());
    }

    /**
     * 认证失败
     */
    @ExceptionHandler(NotLoginException.class)
    public Result<?> handleNotLoginException(NotLoginException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        if (e.getType().equals(TOKEN_TIMEOUT)) {
            log.error("请求地址'{}',认证超时'{}',无法访问系统资源", requestURI, e.getMessage());
            return error(StatusCode.AUTH_TIMEOUT.getCode(), StatusCode.AUTH_TIMEOUT.getMsg());
        } else {
            log.error("请求地址'{}',认证失败'{}',无法访问系统资源", requestURI, e.getMessage());
            return error(StatusCode.AUTH_FAILED.getCode(), StatusCode.AUTH_FAILED.getMsg());
        }
    }
}
